from flask import Blueprint, url_for, render_template, request, current_app,redirect, abort, flash
from app import db
from app.utils.common import login_required
from app.utils.util import upload_image, delete_image
from app.models import Article, Category, Tag
from app.constants import PAGE_LIMIT
from app.forms import ArticleForm
from datetime import datetime

article_controller = Blueprint("article", __name__)

@article_controller.route("/article/index")
@login_required
def article():
    page = request.args.get("page", 1, type=int)
    try:
        pagination = Article.query.order_by(Article.id.desc()).paginate(page, per_page=PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)
        flash("获取文章失败")

    return render_template('admin/article/index.html', pagination=pagination)

@article_controller.route("/article/add", methods=['GET', 'POST'])
@login_required
def add_article():
    category = Category.query.order_by(Category.sort.asc()).all()
    tag = Tag.query.order_by(Tag.id.asc()).all()
    form = ArticleForm()
    form.category_id.choices = [(c.id, c.catname) for c in category]
    form.category_id.choices.insert(0, (0, '请选择栏目'))

    form.keywords.choices = [(c.id, c.tagname) for c in tag]

    if request.method == "POST":
        if form.validate_on_submit():

            category_id = form.data.get('category_id')
            title = form.data.get('title')
            author = form.data.get('author')
            description = form.data.get('description')
            content = form.data.get('content')
            is_state = form.data.get('is_state')

            keywords = form.data.get('keywords', [])

            # 上传图片
            result = upload_image(request, 'pic')
            pic = result.get('url', '')

            try:
                tags = Tag.query.filter(Tag.id.in_(keywords)).all()
                article = Article(
                    category_id=category_id,
                    admin_id = 1,
                    title=title,
                    author=author, 
                    description=description,
                    content=content,
                    pic=pic,
                    is_state=is_state,
                    keywords=''
                )
                article.tags = tags
                db.session.add(article)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加文章失败")
            return redirect(url_for('article.article'))
        
    return render_template("admin/article/add.html", form=form)

@article_controller.route("/article/edit", methods=['GET', 'POST'])
@login_required
def edit_article():
    id = request.args.get("id", 0)
    try:
        article = Article.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("文章不存在")
        return redirect(url_for('article.article'))

    tag = Tag.query.order_by(Tag.id.asc()).all()
    category = Category.query.order_by(Category.sort.asc()).all()
    form = ArticleForm(
        title=article.title,
        category_id=article.category_id,
        author=article.author,
        description = article.description,
        keywords = [t.id for t in article.tags],
        click = int(article.click)
    )
    form.category_id.choices = [(c.id, c.catname) for c in category]
    form.category_id.choices.insert(0, (0, '请选择栏目'))

    form.keywords.choices = [(c.id, c.tagname) for c in tag]

    if request.method == "POST":
        if form.validate_on_submit():
            category_id = form.data.get('category_id')
            title = form.data.get('title')
            author = form.data.get('author')
            description = form.data.get('description')
            content = form.data.get('content')
            is_state = form.data.get('is_state')

            keywords = form.data.get('keywords', [])

            # 上传图片
            image = request.files.get("pic")
            if image.filename:
                result = upload_image(request, 'pic')
                pic = result.get('url', '')
                article.pic = pic

            article.title = title
            article.category_id = category_id
            article.author = author
            article.description = description
            article.content = content
            article.is_state = is_state
            article.update_time = datetime.now()
            try:
                tags = Tag.query.filter(Tag.id.in_(keywords)).all()
                article.tags = tags
                db.session.add(article)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑文章失败")
            return redirect(url_for('article.article'))
        
    return render_template("admin/article/edit.html", form=form, article=article)

@article_controller.route("/article/delete", methods=['GET'])
@login_required
def del_article():
    id = request.args.get("id", 0, type=int)

    try:
        article = Article.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("文章不存在")
        return redirect(url_for('article.article'))
    
    if article:
        try:
            db.session.delete(article)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            flash("删除文章失败")

    return redirect(url_for('article.article'))